dojo.provide("miaigo.view.BaseView");

dojo.require("dijit.layout.ContentPane");

dojo.declare(
    "miaigo.view.BaseView",
    [dijit.layout.ContentPane],
    {
	_controller: null,
	_connHandles: null,

	// connection definitions
	// {
	//   inbound: [],
	//   outbound: []
	// }
	// - inbound is array of
	//   {
	//     event: "eventName", (controller event)
	//     method: "methodName" (view method)
	//   }
	// - outbound is array of
	//   {
	//     event: "eventName", (view event)
	//     method: "methodName" (controller method)
	//   }
	_connDefs: null,

	// When attached by a controller,
	// a view can setup connections between controller and itself
	onAttached: function(controller)
	{
	    if (this._controller)
	    {
		this.onDetached(this._controller);
	    }

	    if (!this._controller)
	    {
		this._controller = controller;
		this._connHandles = [];

		if (this._connDefs && dojo.isArray(this._connDefs.inbound))
		{
		    dojo.forEach
		    (
			this._connDefs.inbound,
			function(connDef)
			{
			    var handle = this.connect
			    (
				controller,
				connDef.event,
				connDef.method
			    );
			    this._connHandles.push(handle);
			},
			this
		    );
		}

		if (this._connDefs && dojo.isArray(this._connDefs.outbound))
		{
		    dojo.forEach
		    (
			this._connDefs.outbound,
			function(connDef)
			{
			    var handle = dojo.connect
			    (
				this,
				connDef.event,
				controller,
				connDef.method
			    );
			    this._connHandles.push(handle);
			},
			this
		    );
		}
	    }
	},

	// release the connections between view and controller
	onDetached: function(controller)
	{
	    if (controller == this._controller)
	    {
		if (this._connHandles)
		{
		    for (var i in this._connHandles)
		    {
			this.disconnect(this._connHandles[i]);
		    }

		    this._connHandles = null;
		}

		this._controller = null;
	    }
	}
    });